## general definitions of the class and generic function

##################################################################
# Set up the generics
##################################################################
setGeneric("readData", function(time, cusip, ...) {standardGeneric("readData")})
setGeneric("getData", function(.Object, ...) {standardGeneric("getData")})
##################################################################
# Set up parameters
##################################################################
# This is a temporary path to data file location
dataFileName <- "~/Dropbox/wrdsdata/crsp2011.csv"
##################################################################
# Market Data class declaration
##################################################################
setClass("MktData", representation(fileName = "character"))
# read and format data from raw file
setMethod("getData", signature = c(.Object = "MktData"),
          def = function(.Object) {
            # read in data via csv, might change to SQL to speed up
            ret <- read.csv(.Object@fileName, colClasses = c(rep("character", 8), rep("numeric", 19)))
            ret$Date <- as.Date(ret$DATE, "%Y%m%d")
            return(ret)
          })
# the function parameter to readData interface for Date argument
dataReaderDate <- function(time, cusip, ...) {
  dataFile <- new("MktData", fileName = dataFileName)
  tmpData <- getData(dataFile)
  colNum <- c(28, 8, 18, 23, 12, 15)
  if (length(time) == 2) { # range
    time <- sort(time)
    print(cusip)
    ind <- with(tmpData, which(Date >= time[1] & Date <= time[2]  & CUSIP %in% cusip))
    print(length(ind))
    ret <- tmpData[ind, colNum]
  } else { # list
    time <- sort(time)
    ind <- with(tmpData, which(Date %in% time & CUSIP %in% cusip))
    ret <- tmpData[ind, colNum]
  }
  names(ret) <- c("date", "ticker", "price", "split", "dividend", "shares")
  return (ret)
}
# the function parameter to readData interface for string argument
dataReaderStr <- function(time, cusip, ...) {
  date <- as.Date(time, "%Y-%m-%d")
  readData(date, cusip)
}

